package logic;

import gui.SearchResultScreen;

import java.util.Vector;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;

/**
 * class for finding active clients
 * @author Rekin
 *
 */
public class BtServerConnection implements DiscoveryListener{

	private Vector foundDevicesOnline; //RemoteDevice
	private Vector foundServicesWithGame; //ServiceRecord
	private DiscoveryAgent discoveryAgent;
	private int searchServices;
	
	/**
	 * default constructor
	 */
	public BtServerConnection() {
		searchServices=-1;
		foundDevicesOnline=new Vector();
		foundServicesWithGame=new Vector();
		startListening();
	}
	
	/**
	 * method for canceling the server inquiring
	 */
	public void stopListening(){
		discoveryAgent.cancelInquiry(this);
		if(searchServices!=-1) //if started looking for services stop this
			discoveryAgent.cancelServiceSearch(searchServices);
	}
	
	/**
	 * starts inquiring for devices
	 */
	private void startListening(){
		try{
			discoveryAgent = LocalDevice.getLocalDevice().getDiscoveryAgent();
			discoveryAgent.startInquiry( DiscoveryAgent.GIAC, this);
		}
		catch(BluetoothStateException e){
			makeErrorPopup("Bluetooth error: "+e.getMessage());
		}
		catch(Exception e){
			makeErrorPopup("Error: "+e.getMessage());
		}
	}
	
	/**
	 * creates an inner popup
	 * @param popupText
	 */
	private void makeErrorPopup(String popupText){
		Alert erropPopup= LogicHelper.makePopup("Error", popupText, 3000, AlertType.ERROR);
        MainMidlet.getMidletInstance().setDisplay(erropPopup);
	}

	/**
	 * method called by system when bluetooth device is found
	 * @param btDevice found device device
	 * @param devClass device class
	 */
	public void deviceDiscovered(RemoteDevice btDevice, DeviceClass devClass) {
		if(devClass.getMajorDeviceClass() == LogicHelper.MAYOR_DEVICE_CLASS_PHONE){
			if(!foundDevicesOnline.contains(btDevice)){
				foundDevicesOnline.addElement(btDevice);
			}
		}
	}

	/* (non-Javadoc)
	 * @see javax.bluetooth.DiscoveryListener#inquiryCompleted(int)
	 */
	public void inquiryCompleted(int inquiryType) { //found all bt devices
		//start search for service of game
		if(inquiryType == INQUIRY_COMPLETED){
			if(foundDevicesOnline.size()>0){
				UUID[] serviceUidsToSearch = new UUID[] {
						new UUID(LogicHelper.serviceUUID,false)
				};
				for(int i=0;i<foundDevicesOnline.size();++i){
					try{
						searchServices = discoveryAgent.searchServices(
								LogicHelper.serviceAttributes, serviceUidsToSearch,
								(RemoteDevice)foundDevicesOnline.elementAt(i),
								this);
					}
					catch(BluetoothStateException e){
						makeErrorPopup("Error "+ e.getMessage());
					}
				}
			}
			else{
				MainMidlet.getMidletInstance().setDisplay(
						new SearchResultScreen(foundServicesWithGame));
			}
		}
	}

	/* (non-Javadoc)
	 * @see javax.bluetooth.DiscoveryListener#servicesDiscovered(int, javax.bluetooth.ServiceRecord[])
	 */
	public void servicesDiscovered(int arg0, ServiceRecord[] arg1) {
		foundServicesWithGame.addElement(arg1[0]);
	}
	
	/* (non-Javadoc)
	 * @see javax.bluetooth.DiscoveryListener#serviceSearchCompleted(int, int)
	 */
	public void serviceSearchCompleted(int transID, int respCode) {
		if(respCode==DiscoveryListener.SERVICE_SEARCH_COMPLETED){
			MainMidlet.getMidletInstance().setDisplay(
				new SearchResultScreen(foundServicesWithGame));
		}
		else if(respCode==DiscoveryListener.SERVICE_SEARCH_NO_RECORDS){
			MainMidlet.getMidletInstance().setDisplay(
				new SearchResultScreen(foundServicesWithGame));
		}
		
	}
}
